package cn.xqj.basic.interceptor;


import cn.xqj.basic.annotation.PreAuthorize;
import cn.xqj.basic.jwt.JwtUtils;
import cn.xqj.basic.jwt.LoginData;
import cn.xqj.basic.jwt.Payload;
import cn.xqj.basic.jwt.RsaUtils;
import cn.xqj.org.mapper.EmployeeMapper;
import cn.xqj.user.domain.Logininfo;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.List;


@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token != null) {
            PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
            try {
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                if (payload != null) {
                    Logininfo logininfo = payload.getLoginData().getLogininfo();
                    if (logininfo.getType() == 1) {
                        return true;
                    }

                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    PreAuthorize annotation = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    if (annotation == null) {
                        return true;
                    } else {
                        List<String> sns = employeeMapper.findSnByLogininfoId(logininfo.getId());
                        if (sns.contains(annotation.sn())) {
                            return true;
                        } else {
                            // 响应数据到前端
                            response.setContentType("Application/json;charset=utf-8");
                            response.getWriter().println("{\"success\":false,\"msg\":\"noPermission\"}");
                            return false;
                        }
                    }
                }
            } catch (ExpiredJwtException e) {
                e.printStackTrace();
                // 响应数据到前端
                response.setContentType("Application/json;charset=utf-8");
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
                return false;
            }

        }

        // 响应数据到前端
        response.setContentType("Application/json;charset=utf-8");
        response.getWriter().println("{\"success\":false,\"msg\":\"nologin\"}");
        return false;

    }
}
